package com.gopay.checkorder.service.task.thread;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import com.gopay.checkorder.service.BankOrderService;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.util.DateUtils;

public class BocDayendTaskThread implements Runnable {

	@Resource(name = "bankOrderService")
	private BankOrderService bankOrderService;

	@Resource(name = "mailSender")
	private JavaMailSenderImpl mailSender;
	
	@Resource(name="mailPerson")
	private Map<String,String> mailPerson;
	
	private static final String bank_bus = "BOC-B2C";
	
	@Override
	public void run() {
		Logger log = Logger.getLogger(this.getClass());
		String date = DateUtils.format(new Date(), "yyyy-MM-dd");
		List<CheckOrderResult> checkOrderReList = bankOrderService.checkDayend(bank_bus);
		//有本地数据库出发去查找存在于日终文件中的订单，对其状态进行对单
		//List<CheckOrderResult> checkOrderReList = bankOrderService.checkDayend(bank_bus);
		//拼装邮件体
		String body = "<table><tr><td  colspan='3' align='center' >中行B2C"+date+"对账报警：失败单数"+checkOrderReList.size()+"笔</td></tr><tr><td  align='center' width='200px'>订单号</td><td  align='center' width='200px'>订单金额</td><td  align='center' width='200px'>对单失败原因</td></tr>";
		if(StringUtils.equals("本日无失败订单",checkOrderReList.get(0).getErrMsg())){
			body = "<table><tr><td  colspan='3' align='center' >中行B2C"+date+"对账报警：失败单数"+0+"笔</td></tr><tr><td  align='center' width='200px'>订单号</td><td  align='center' width='200px'>订单金额</td><td  align='center' width='200px'>对单失败原因</td></tr>";
		}
		for (CheckOrderResult checkOrderResult : checkOrderReList) {
				body+="<tr><td  align='center' width='200px'>"+checkOrderResult.getOrderId() + "</td><td  align='center' width='200px'>"+ checkOrderResult.getAmount() + "</td><td  align='center' width='600px'>"+ checkOrderResult.getErrMsg()+"</td></tr>";
		}
		body+="</table>";
		MimeMessage mailMessage = mailSender.createMimeMessage();
		try {
			mailMessage.setContent(body, "text/html;charset = UTF-8");
			mailMessage.setSubject("中国银行B2C对账报警");
			mailMessage.setFrom(new InternetAddress(mailPerson.get("from")));  
	        mailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailPerson.get("to")));
			mailSender.send(mailMessage);
		} catch (Exception e) {
			log.error("send mail fail",e);
		}
		
		
	}

	public void setBankOrderService(BankOrderService bankOrderService) {
		this.bankOrderService = bankOrderService;
	}

	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	public void setMailPerson(Map<String, String> mailPerson) {
		this.mailPerson = mailPerson;
	}
	
}
